package com.ds.infra.mq.core.server;

import com.ds.infra.mq.core.config.BrokerConfig;
import com.ds.infra.mq.core.config.NettyConfig;
import com.ds.infra.mq.core.config.StorageConfig;
import com.ds.infra.mq.core.network.NettyServer;
import com.ds.infra.mq.core.network.RequestProcessor;
import com.ds.infra.mq.core.network.ServerHandler;
import com.ds.infra.mq.core.storage.MemoryMessageStore;
import lombok.extern.slf4j.Slf4j;

/**
 * 作用：启动MQ消息队列的Broker服务
 *
 * @author WeiShaoying
 */
@Slf4j
public class Broker {

    private final BrokerConfig brokerConfig;
    private final NettyConfig nettyConfig;
    private final StorageConfig storageConfig;
    private NettyServer nettyServer;

    public Broker(BrokerConfig brokerConfig,
                  NettyConfig nettyConfig,
                  StorageConfig storageConfig) {
        this.brokerConfig = brokerConfig;
        this.nettyConfig = nettyConfig;
        this.storageConfig = storageConfig;
    }

    public void start() {
        log.info("Starting InfraMQ broker...");
        MemoryMessageStore messageStore = new MemoryMessageStore(storageConfig);
        RequestProcessor requestProcessor = new RequestProcessor(messageStore);
        nettyServer = new NettyServer(brokerConfig, nettyConfig, new ServerHandler(requestProcessor));

        try {
            nettyServer.start();
        } catch (InterruptedException e) {
            log.error("Broker interrupted", e);
            Thread.currentThread().interrupt();
        }
    }

    public void shutdown() {
        log.info("Shutting down InfraMQ broker...");
        if (nettyServer != null) {
            nettyServer.shutdown();
        }
    }
}
